package com.l024.meet.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.view.View;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.l024.framework.bmob.BmobManager;
import com.l024.framework.cloud.CloudManager;
import com.l024.framework.db.LitePalHelper;
import com.l024.framework.db.NewFriend;
import com.l024.framework.entity.Constants;
import com.l024.framework.event.EventBusManager;
import com.l024.framework.gson.TextBean;
import com.l024.framework.utils.CommonUtils;
import com.l024.framework.utils.Logutils;
import com.l024.framework.utils.SpUtils;

import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

public class CloudService extends Service {
    private Disposable disposable;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        linkCloudService();
    }

    /**
     * 连接融云
     */
    private void linkCloudService(){
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN, "");
        //连接融云
        CloudManager.getInstance().connect(token);
        //接受消息
        CloudManager.getInstance().setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {
                Logutils.i("接受消息:"+message);
                String objectName = message.getObjectName();
                //文本消息
                if(objectName.equals(CloudManager.MSG_TEXT_NAME)){
                    TextMessage textMessage = (TextMessage)message.getContent();
                    //获取内容
                    String content = textMessage.getContent();
                    //判断是否是添加好友消息
                    TextBean textBean = new Gson().fromJson(content,TextBean.class);
                    if(textBean!=null){
                        if(CloudManager.TYPE_TEXT.equals(textBean.getType())){
                            //普通文本消息
                            Logutils.e("普通消息:"+textBean.getMsg());

                        }else if(CloudManager.TYPE_ADD_FRIEND.equals(textBean.getType())){
                            //添加好友的消息
                            Logutils.e("收到添加好友消息:"+textBean.getMsg());
                            //查询数据库，没有才保存
                            disposable = Observable.create(new ObservableOnSubscribe<List<NewFriend>>() {
                                @Override
                                public void subscribe(ObservableEmitter<List<NewFriend>> emitter) throws Exception {
                                    emitter.onNext(LitePalHelper.getInstance().queryNewFriend());
                                    emitter.onComplete();
                                }
                            }).subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<List<NewFriend>>() {
                                    @Override
                                    public void accept(List<NewFriend> newFriends) throws Exception {
                                        //数据库没有才添加
                                        if(CommonUtils.isEmpty(newFriends)){
                                            boolean isHava = false;
                                            for(NewFriend newFriend:newFriends){
                                                if(message.getSenderUserId().equals(newFriend.getUserId())){
                                                    isHava = true;
                                                    break;
                                                }
                                            }
                                            if(!isHava){
                                                //存入本地数据库
                                                LitePalHelper.getInstance().savaNewFriend(textBean.getMsg(),message.getSenderUserId());
                                            }
                                        }else{
                                            //存入本地数据库
                                            LitePalHelper.getInstance().savaNewFriend(textBean.getMsg(),message.getSenderUserId());
                                        }
                                    }
                                });

                        }else if(CloudManager.TYPE_AGREED_FRIEND.equals(textBean.getType())){
                            //同意添加好友
                            //1.添加到好友列表
                            BmobManager.getInstance().addFriend(message.getSenderUserId(), new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if(e==null){
                                        //添加成功，刷新好友列表
                                        EventBusManager.post(EventBusManager.FLAY_UPDATE_FRIEND_LIST);
                                    }else{
                                        Logutils.e("添加同意好友失败"+e);
                                    }
                                }
                            });
                        }
                    }
                }
                return false;
            }
        });


    }
}
